//
//  415. 字符串相加.swift
//  Top600
//
//  Created by rjb on 2021/8/8.
//

import Foundation
class Solution415 {
    // 字符串形式的数字
    // 输出也是字符串的形式
    func addStrings(_ num1: String, _ num2: String) -> String {
        let num1Array:[Character] = Array(num1)
        let num2Array:[Character] = Array(num2)
        var p1 = num1.count - 1
        var p2 = num2.count - 1
        var stepIn = false // 是否进位
        var result: String = ""
        while p1 >= 0 || p2 >= 0 {
            var v1 = 0
            var v2 = 0
            if p1 >= 0 {
                v1 = num1Array[p1].wholeNumberValue ?? 0
            }
            if p2 >= 0 {
                v2 = num2Array[p2].wholeNumberValue ?? 0
            }
            var localSum = v1 + v2 + (stepIn ? 1 : 0)
            stepIn = localSum / 10 == 0 ? false : true
            localSum = localSum % 10
            result.insert(Character(String(localSum)), at: result.startIndex)
            p1 -= 1
            p2 -= 1
        }
        if stepIn {
            result.insert(Character(String("1")), at: result.startIndex)
        }
        return result
    }
    static func test(){
        let solution = Solution415()
        let num1 = "123"
        let num2 = "3891"

        let result = solution.addStrings(num1, num2)
        print(result)
    }
}
